let socket : any = null;

export const socketCoonnect = (socketUrl : string) => {
    if(!socketUrl) {
        throw new Error("socketUrl is required");
    }
    socket = new WebSocket(`${socketUrl}`);

    // 断点重连
    socket.addEventListener('close', function() {
        console.warn('socket close');
        socket.close();
        socket = null;
        setTimeout(() => {
            socketCoonnect(socketUrl);
        }, 3000);
    })

    return socket;
}

// 发送事件
export const socketSend = (sendData : Record<string, any>) => {
    if(!socket) {
        throw new Error("socket is not connected");
    }
    if(typeof sendData !== "object") {
        throw new Error("sendData must be object");
    }
    socket.send(JSON.stringify(sendData));
}

export const socketClose = () => {
    if(!socket) {
        throw new Error("socket is not connected");
    }
    socket.close();
}

export const socketOnMessage = (callback : (res : any) => void) => {
    if(!socket) {
        throw new Error("socket is not connected");
    }
    socket.onmessage = (res : any) => {
        callback(res);
    }
}